package org.gorkr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.gorkr.dao.UserInfoMapper;
import org.gorkr.domain.User;
import org.gorkr.dao.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.gorkr.domain.UserInfo;
import org.gorkr.domain.constant.UserConstant;
import org.gorkr.domain.exception.ConditionException;
import org.gorkr.service.IUserService;
import org.gorkr.service.util.MD5Util;
import org.gorkr.service.util.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author gorkr
 * @since 2022-08-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void addUser(User user) {
        String phone = user.getPhone();
        if (StringUtils.isNullOrEmpty(phone)) {
            // 通过通用异常,返回给前端
            throw new ConditionException("手机号不能为空!");
        }
        // 从db查找是否用户存在
        User dbUser = this.getUserByPhone(phone);
        if(dbUser!=null){
            throw new ConditionException("该手机号已经注册");
        }
        // 通过时间戳生成一个salt
        LocalDateTime now = LocalDateTime.now();
        String salt = now.toString();

        // 前端传来的 password
        String password = user.getPassword();

        // 模拟前端加密
        try {
            password = RSAUtil.encrypt(password);
        }catch (Exception e){
            e.printStackTrace();
            throw new ConditionException("模拟前端加密失败");
        }


        // 解密password
        String rawPassword;
        try {
            rawPassword = RSAUtil.decrypt(password);
        }catch (Exception e){
            e.printStackTrace();
            throw new ConditionException("密码解密失败");
        }

        // 填充user数据库对象
        String md5Password = MD5Util.sign(rawPassword, salt, "UTF-8");
        user.setSalt(salt);
        user.setPassword(md5Password);
        user.setCreateTime(now);
        user.setUpdateTime(now);

        // todo 插入失败怎么处理
        userMapper.insert(user);

        // 填充userInfo数据库对象
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setNick(UserConstant.DEFAULT_NICK);
        userInfo.setBirth(UserConstant.DEFAULT_BIRTH);
        userInfo.setGender(UserConstant.GENDER_MALE);
        userInfo.setCreateTime(now);
        userInfoMapper.insert(userInfo);
    }

    private User getUserByPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return userMapper.selectOne(wrapper);
    }
}
